import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '../stores/user'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: {
      title: '首页'
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/LoginView.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/login-debug',
    name: 'LoginDebug',
    component: () => import('../views/LoginDebug.vue'),
    meta: {
      title: '登录调试',
      requiresAuth: false
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/RegisterView.vue'),
    meta: {
      title: '注册',
      requiresAuth: false
    }
  },
  {
    path: '/add-category',
    name: 'AddCategory',
    component: () => import('../views/AddCategory.vue'),
    meta: {
      title: '添加课程类别',
      requiresAuth: true
    }
  },
  {
    path: '/add-course',
    name: 'AddCourse',
    component: () => import('../views/AddCourse.vue'),
    meta: {
      title: '添加课程',
      requiresAuth: true
    }
  },
  {
    path: '/add-subitem',
    name: 'AddSubitem',
    component: () => import('../views/AddSubitem.vue'),
    meta: {
      title: '添加课程任务项',
      requiresAuth: true
    }
  },
  {
    path: '/course/detail/:id',
    name: 'CourseDetail',
    component: () => import('../views/CourseDetail.vue'),
    meta: {
      title: '课程详情',
      requiresAuth: true
    }
  }]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  }
  
  const userStore = useUserStore()
  const isAuthenticated = userStore.userInfo.isLogin
  
  // 需要认证的页面，但用户未登录
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

export default router